package cn.innosmart.aq.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.GravityCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;

import org.json.JSONException;
import org.json.JSONObject;

import cn.innosmart.aq.R;
import cn.innosmart.aq.customize.ModifyPasswordDialog;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.base.BaseActivity;

/**
 * Created by David on 2015/7/28.
 */
public class CountSettingActivity extends BaseActivity implements INetworkInteractUtil {
    private final int EXIT = 0;
    private final int MODIFYNICKNAME = 2;
    private NetworkInteractUtil networkInteractUtil;
    private ImageView headIcon;
    private ImageView ivModifyNickName;
    private RelativeLayout rlModifyPassword;
    private RelativeLayout rlSecuritySetting;
    private RelativeLayout rlAssign;
    private Button btLogOut;
    private TextView nickName;
    /**
     * 设置toolbar
     */

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXIT:
                    exit();
                    break;
                case MODIFYNICKNAME:
                    switchToModifyNickNameActivity();
                    break;
            }
        }
    };
    private View.OnClickListener mBtnOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.iv_modify_nick_name:
                    mHandler.sendEmptyMessage(MODIFYNICKNAME);
                    break;
                case R.id.rl_modify_password:
                    showModifyPasswordDialog();
                    break;
                case R.id.rl_security_setting:
                    break;
                case R.id.rl_assign:
                    Intent intent = new Intent(CountSettingActivity.this, AssignActivity.class);
                    startActivity(intent);
                    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    break;
                case R.id.bt_log_out:
                    clearUserData();
                    setResult(RESULT_OK);
                    mHandler.sendEmptyMessage(EXIT);
                    break;
            }
        }
    };
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_count_setting);
        setBar();
        assignViews();
        setListener();
        networkInteractUtil = new NetworkInteractUtil(this);
    }

    private void assignViews() {
        ivModifyNickName = (ImageView) findViewById(R.id.iv_modify_nick_name);
        rlModifyPassword = (RelativeLayout) findViewById(R.id.rl_modify_password);
        headIcon = (ImageView) findViewById(R.id.head_icon);
        rlSecuritySetting = (RelativeLayout) findViewById(R.id.rl_security_setting);
        rlAssign = (RelativeLayout) findViewById(R.id.rl_assign);
        btLogOut = (Button) findViewById(R.id.bt_log_out);
        nickName = (TextView) findViewById(R.id.nick_name);
        headIcon.setImageResource(R.drawable.head_icon);
//        rlAssign.setVisibility(View.VISIBLE);
        findViewById(R.id.divide_line).setVisibility(View.VISIBLE);
    }

    private void setListener() {
        ivModifyNickName.setOnClickListener(mBtnOnClickListener);
        rlModifyPassword.setOnClickListener(mBtnOnClickListener);
        rlSecuritySetting.setOnClickListener(mBtnOnClickListener);
        rlAssign.setOnClickListener(mBtnOnClickListener);
        btLogOut.setOnClickListener(mBtnOnClickListener);
    }

    private void clearUserData() {
        SystemConstant.loginStatus = SystemConstant.Offline;
        SystemConstant.employees = null;
        SystemConstant.server_uid = null;
        SystemConstant.session_token = null;
        SystemConstant.username = null;
        SharedUtil.getInstance().clearLoginInfo();
        SharedUtil.getInstance().clearGatewayInfo();
        SystemConstant.boxBeanList.clear();
    }

    private void setBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.activity_count_setting));
        setSupportActionBar(toolbar);
//        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mHandler.sendEmptyMessage(EXIT);
//            }
//        });
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mDrawer.openDrawer(GravityCompat.START);
                mHandler.sendEmptyMessage(EXIT);
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    private void switchToModifyNickNameActivity() {
        Intent intent = new Intent(CountSettingActivity.this, ModifyNickNameActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }


    @Override
    protected void onResume() {
        setBaseDialogContext(this);
        nickName.setText(SystemConstant.nickname);
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    public void showModifyPasswordDialog() {
        final ModifyPasswordDialog modifyPasswordDialog = new ModifyPasswordDialog(this);
        final EditText etOldPassword = (EditText) modifyPasswordDialog.findViewById(R.id.et_old_password);
        final EditText etNewPassword = (EditText) modifyPasswordDialog.findViewById(R.id.et_new_password);
        final EditText etNewPasswordSure = (EditText) modifyPasswordDialog.findViewById(R.id.et_new_password_sure);
        modifyPasswordDialog.setTitle(R.string.dialog_title_alert);
        modifyPasswordDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String oldPassword = etOldPassword.getText().toString().trim();
                final String newPassword = etNewPassword.getText().toString().trim();
                String newPasswordSure = etNewPasswordSure.getText().toString().trim();
                if (TextUtils.isEmpty(oldPassword)) {
                    showToast(getString(R.string.activity_countsetting_old_password_can_not_empty));
                    YoYo.with(Techniques.Shake).playOn(etOldPassword);
                    return;
                }
                if (TextUtils.isEmpty(newPassword)) {
                    showToast(getString(R.string.activity_countsetting_input_new_password));
                    YoYo.with(Techniques.Shake).playOn(etNewPassword);
                    return;
                }
                if (TextUtils.isEmpty(newPasswordSure)) {
                    showToast(getString(R.string.activity_countsetting_sure_new_password));
                    YoYo.with(Techniques.Shake).playOn(etNewPasswordSure);
                    return;
                }
                if (!newPassword.equals(newPasswordSure)) {
                    showToast(getString(R.string.activity_countsetting_twice_password_not_same));
                    YoYo.with(Techniques.Shake).playOn(etNewPassword);
                    YoYo.with(Techniques.Shake).playOn(etNewPasswordSure);
                    return;
                }
                try {
                    String oldPasswordSure = SharedUtil.getInstance().readLoginInfo().getString("password");
                    if (!oldPasswordSure.equals(oldPassword)) {
                        showToast(getString(R.string.activity_countsetting_old_password_wrong));
                        etOldPassword.setText("");
                        YoYo.with(Techniques.Shake).playOn(etOldPassword);
                        return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                JSONObject jsParam = new JSONObject();
                try {
                    jsParam.put("password", oldPassword);
                    jsParam.put("new_password", newPassword);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                networkInteractUtil.syncModifyPassword(jsParam, new INetworkInteractUtil() {
                    @Override
                    public void onNetworkInteractAllOver(int ret) {

                    }

                    @Override
                    public void onNetworkInteractOver(int ret, String flag, Object object) {
                        if (flag.equals(networkInteractUtil.MODIFYPASSWORD)) {
                            if (ret == 0) {
                                showToast(getString(R.string.modify_success));
                                SharedUtil.getInstance().updateLoginPassword(newPassword);
                                modifyPasswordDialog.dismiss();
                            } else if (ret == -1) {
                                showToast(getString(R.string.modify_failed));
                            }
                        }
                    }
                });
            }
        });
        modifyPasswordDialog.setNegativeButton(getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modifyPasswordDialog.dismiss();
            }
        });
        modifyPasswordDialog.setCanceledOnTouchOutside(false);
        modifyPasswordDialog.show();
    }

    @Override
    public void onNetworkInteractAllOver(int ret) {

    }

    @Override
    public void onNetworkInteractOver(int ret, String flag, Object object) {

    }
}
